/*
 * FinishedQ.cpp
 *
 *  Created on: Nov 21, 2013
 *      Author: sickan
 */

#include "FinishedQ.h"
#include <stdio.h>
#include <iostream>
#include <pthread.h>
#include "string"

FinishedQ* FinishedQ::instance = NULL;

FinishedQ* FinishedQ::getInstance() {
	if(instance == NULL) {
		 instance = new FinishedQ();
	}
	return instance;
}

int FinishedQ::getFinishedQSize() {
	return queue.size();
}

void FinishedQ::displaySummary() {
	pthread_mutex_lock(&finishQMutex);
	double size = queue.size();
	double averageLifeTime = 0;
	double averagePriorityQTime = 0;
	double averageCPUTime = 0;
	double averageBlockQTime = 0;
	for (std::list<Process*>::iterator p = queue.begin(); p != queue.end(); p++) {
		printf("Process%d - total lifetime: %.2f ms PriorityQ time: %.2f ms CPU time: %.2f ms BlockedQ time: %.2f ms \n",
				(*p)->getProcessID(), (*p)->getTotalLifetime(), (*p)->getReadyQTime(), (*p)->getCpuTime(), (*p)->getBlockedQTime());
		averageLifeTime += (*p)->getTotalLifetime();
		averagePriorityQTime += (*p)->getReadyQTime();
		averageCPUTime += (*p)->getCpuTime();
		averageBlockQTime += (*p)->getBlockedQTime();
	}

	printf("\nSummary: \n\tAverage process lifetime: %.2f ms \n\tAverage process PriorityQ time: %.2f ms \n\tAverage process BlockedQ time: %.2f ms \n\tAverage process CPU time: %.2f ms \n",
			(averageLifeTime / size),
			(averagePriorityQTime / size),
			(averageBlockQTime / size),
			(averageCPUTime / size));


	pthread_mutex_unlock(&finishQMutex);
}

FinishedQ::FinishedQ() {
	queue = std::list<Process*>();
	finishQMutex = PTHREAD_MUTEX_INITIALIZER;
}

FinishedQ::~FinishedQ() {
	// TODO Auto-generated destructor stub
}

void FinishedQ::add(Process* p) {
	pthread_mutex_lock(&finishQMutex);
	p->stopTimer(Process::LifeTime);
	queue.push_back(p);
	pthread_mutex_unlock(&finishQMutex);
	printf("FinishedQ: Process%d is finished\n", p->getProcessID());
}
